/**
 * @author pengyajun
 * @description AsyncStorage Helper
 */
import { AsyncStorage } from 'react-native';

class StorageHelper {

  static async set (key, value) {
    try {
      if (typeof value == "object") {
        value = JSON.stringify(value);
      } else {
        value = value.toString();
      }
      return await AsyncStorage.setItem(key, value);
    } catch (error) {
      return;
    }
  }

  static async get (key, callback) {
    try {
      return await AsyncStorage.getItem(key, callback);
    } catch (error) {
      return;
    }
  }

  static async remove (key, callback) {
    try {
      return await AsyncStorage.removeItem(key, callback);
    } catch (error) {
      return;
    }
  }

  static async update (key, value, callback) {
    try {
      if (typeof value == "object") {
        value = JSON.stringify(value);
      } else {
        value = value.toString();
      }
      return await AsyncStorage.mergeItem(key, value, callback);
    } catch (error) {
      return;
    }
  }

  /**
   * 
   * @param {Array<Array<string>>} keyValuePairs [['k1', 'val1'], ['k2', 'val2']]
   * @param {?(errors: ?Array<Error>} callback 
   *  val 必须是String
   */
  static async multiSet (keyValuePairs, callback) {
    try {
      for (let obj of keyValuePairs) {
        if (obj.length != 2) return;
        let value = obj[1];
        if (typeof value == "object") {
          value = JSON.stringify(value);
        } else {
          value = value.toString();
        }
        obj[1] = value;
      }
      return await AsyncStorage.multiSet(keyValuePairs, callback)
    } catch (error) {
      return;
    }
  }

  /**
   * 
   * @param {Array} keys ['k1', 'k2']
   * @param {*} callback 
   */
  static async multiRemove (keys, callback) {
    try {
      return await AsyncStorage.multiRemove(keys, callback)
    } catch (error) {
      return;
    }
  }
}
export default StorageHelper;
